import axios from 'axios'
import store from '@/store'
import { getToken } from '@/utils/auth'
import { Message,MessageBox } from 'element-ui'

// 是否显示重新登录
let isReloginShow;

axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'

// 创建axios实例
const service = axios.create({
  // axios中请求配置有baseURL选项，表示请求URL公共部分
  baseURL: process.env.VUE_APP_PORT,
  // 超时
  timeout: 30000
})

// http request 拦截器
service.interceptors.request.use(config => {

  // console.log(getToken());
  if (getToken()) {
    config.headers.Authorization = 'Bearer ' + getToken()
  }
  return config
}, function (error) {
  // 对请求错误做些什么
  return Promise.reject(error)
})

// http response 拦截器
service.interceptors.response.use(
  resp => {

    // token过期重新请求token
    if (resp.data.code == 401) {
      reLogin()
    }
    if (resp.data.code == 403) {
      Message.warning(resp.data.msg)
    }
    return resp
  },
  error => {
    return Promise.reject(error)
  }
)
/**
 * get请求方法
 * @param {String} url 接口
 * @param {Object} data  请求参数
 * @param {functiong} success 成功回调
 * @param {functiong} failure 失败回调
 * @param {Object} config 配置
 */
const get = function (url, data = {}, success = () => { }, failure = () => { }, config = {}) {
  service.get(url, { params: data }, config)
    .then(resp => {

      if (resp.data.code == 200) {
        success && success(resp.data)
        // token过期重新请求token
      } else if (resp.data.code == 401) {
        reLogin(url, data = {}, success = () => { }, failure = () => { }, config = {}, 'get')
      } else {
        failure && failure(resp.data)
      }
    })
    .catch((error) => {
      failure && failure({ code: 5, msg: '服务器出错，请重新尝试!' })
    })
}


// 通用下载方法
const download = function (url, params, filename) {
  return service.post(url, params, {
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded'
    },
    responseType: 'blob'
  }).then((resp) => {
    // console.log(resp);
    const content = resp.data
    const blob = new Blob([content])
    if ('download' in document.createElement('a')) {
      const elink = document.createElement('a')
      elink.download = filename
      elink.style.display = 'none'
      elink.href = URL.createObjectURL(blob)
      document.body.appendChild(elink)
      elink.click()
      URL.revokeObjectURL(elink.href)
      document.body.removeChild(elink)
    } else {
      navigator.msSaveBlob(blob, filename)
    }
  }).catch((r) => {
    console.error(r)
  })
}



const post = function (url, data = {}, success = () => { }, failure = () => { }, config = {}) {
  service.post(url, data, config)
    .then(resp => {
      if (resp.data.code == 200) {
        success && success(resp.data)
        // token过期重新请求token
      } else if (resp.data.code == 401) {
        reLogin(url, data, success, failure, config, 'post')
      } else {
        failure && failure(resp.data)
      }
    })
    .catch((error) => {
      failure && failure({ code: 5, msg: '服务器出错，请重新尝试!' })
    })
}

const delet = function (url, data = {}, success = () => { }, failure = () => { }, config = {}) {
  service.delete(url, data, config)
    .then(resp => {
      if (resp.data.code == 200) {
        success && success(resp.data)
        // token过期重新请求token
      } else if (resp.data.code == 401) {
        reLogin(url, data, success, failure, config, 'delete')
      } else {
        failure && failure(resp.data)
      }
    })
    .catch((error) => {
      failure && failure({ code: 5, msg: '服务器出错，请重新尝试!' })
    })
}

const put = function (url, data = {}, success = () => { }, failure = () => { }, config = {}) {
  service.put(url, data, config)
    .then(resp => {
      if (resp.data.code == 200) {
        success && success(resp.data)
        // token过期重新请求token
      } else if (resp.data.code == 401) {
        reLogin(url, data, success, failure, config, 'put')
      } else {
        failure && failure(resp.data)
      }
    })
    .catch((error) => {
      console.log('cd', error)
      failure && failure({ code: 5, msg: '服务器出错，请重新尝试!' })
    })
}

//重新登录逻辑方法
const reLogin = function (url, data, success, failure, config, type) {
  if (!isReloginShow) {
    isReloginShow = true;

    MessageBox.confirm('登录状态已过期，您可以继续留在该页面，或者重新登录', '系统提示', {
      confirmButtonText: '重新登录',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {

      isReloginShow = false;
        // 如果是登录页面不需要重新加载
        if (window.location.hash.indexOf("#/login") != 0) {
          location.href = '/index';
        }

    }).catch(() => {
      isReloginShow = false;
    });
  }

  
  // axios.post(LOGIN, {ucToken: store.state.token}, {})
  //   .then(resp => {
  //     if (resp.data.code == 0) {
  //       if (type == 'post') {
  //         post(url, data, success, failure, config)
  //       } else {
  //         get(url, data, success, failure, config)
  //       }
  //     } else {
  //       failure && failure(resp.data)
  //     }
  //   })
  //   .catch((error) => {})
}

export default service

export {
  get,
  download,
  post,
  delet,
  put
}
